package com.ict.datamanagement.common;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * 自动填充 时间字段
 */
@Component
public class AutoFillMetaInfoHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        //填充时间
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "status", String.class, "1");

        // todo 填充userId
        /*HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String authorization = request.getHeader("Authorization");
        Long userId = Long.valueOf(JWT.decode(authorization).getClaim("userId").asString());
        this.strictInsertFill(metaObject, "createBy", Long.class, userId);*/

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //无论属性是否有值都填充
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());

        // 填充userId
        /*HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String authorization = request.getHeader("Authorization");
        Long userId = Long.valueOf(JWT.decode(authorization).getClaim("userId").asString());
        this.strictInsertFill(metaObject, "updateBy", Long.class, userId);*/
    }
}
